﻿using MyUAMS.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;



namespace MyUAMS.BLL
{
    public class CustomerService
    {
        DataClasses1DataContext db = new DataClasses1DataContext();
        public bool IsNameExist(string name)
        {
            User_Table customer = (from c in db.User_Table
                                        where c.Uname == name
                                        select c).FirstOrDefault();
            if(customer !=null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public void Insert(string name, string password, string email)
        {
            string hashedPassword = PasswordHasher.HashPassword(password);
            User_Table customer = new User_Table
            {
                Uname = name,
                Password = hashedPassword,
                Email = email
            };
            db.User_Table.InsertOnSubmit(customer);
            db.SubmitChanges();
        }
        public int CheckLogin(string name, string password)
        {
            User_Table customer = (from c in db.User_Table
                                   where c.Uname == name
                                   select c).FirstOrDefault();
            if (customer != null && PasswordHasher.VerifyPassword(password, customer.Password))
            {
                return customer.Uid;
            }
            else
            {
                return 0;
            }
        }
        public void ChangePassword(int userid, string newPassword)
        {
            User_Table customer = (from c in db.User_Table where c.Uid == userid select c).FirstOrDefault();
            if (customer != null)
            {
                customer.Password = PasswordHasher.HashPassword(newPassword);
                db.SubmitChanges();
            }
        }
        public bool IsEmailExist(string name, string email)
        {
            User_Table customer = (from c in db.User_Table
                                 where c.Uname == name && c.Email == email
                                 select c).FirstOrDefault();
            if (customer != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public void ResetPassword(string name, string email)
        {
            // 生成一个新的随机密码
            string newPassword = GenerateRandomPassword();

            // 使用PasswordHasher类来哈希新密码
            string hashedPassword = PasswordHasher.HashPassword(newPassword);

            // 查询数据库以找到匹配的用户
            User_Table customer = (from c in db.User_Table
                                   where c.Uname == name && c.Email == email
                                   select c).FirstOrDefault();

            // 如果找到了用户，则更新密码
            if (customer != null)
            {
                customer.Password = hashedPassword;
                db.SubmitChanges();

            }
            else
            {

            }
        }
        private string GenerateRandomPassword(int length = 12)
        {
            const string validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            Random random = new Random();
            char[] chars = new char[length];
            for (int i = 0; i < length; i++)
            {
                chars[i] = validChars[random.Next(0, validChars.Length)];
            }
            return new string(chars);
        }


    }


    public class PasswordHasher
    {
        // 生成随机盐
        private static byte[] GenerateSalt()
        {
            byte[] salt = new byte[32]; // 256 bits
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(salt);
            }
            return salt;
        }

        // 创建密码哈希
        public static string HashPassword(string password)
        {
            byte[] salt = GenerateSalt();
            byte[] hash = ComputeHash(password, salt);
            return Convert.ToBase64String(salt) + ":" + Convert.ToBase64String(hash);
        }

        // 验证密码
        public static bool VerifyPassword(string password, string storedHashWithSalt)
        {
            string[] parts = storedHashWithSalt.Split(':');
            byte[] salt = Convert.FromBase64String(parts[0]);
            byte[] hash = Convert.FromBase64String(parts[1]);

            byte[] computedHash = ComputeHash(password, salt);

            return AreHashesEqual(computedHash, hash);
        }

        // 计算哈希值
        private static byte[] ComputeHash(string password, byte[] salt)
        {
            using (var sha256 = SHA256.Create())
            {
                byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
                byte[] saltedPassword = new byte[salt.Length + passwordBytes.Length];
                Buffer.BlockCopy(salt, 0, saltedPassword, 0, salt.Length);
                Buffer.BlockCopy(passwordBytes, 0, saltedPassword, salt.Length, passwordBytes.Length);

                return sha256.ComputeHash(saltedPassword);
            }
        }

        // 比较两个哈希值
        private static bool AreHashesEqual(byte[] firstHash, byte[] secondHash)
        {
            int minHashLength = firstHash.Length <= secondHash.Length ? firstHash.Length : secondHash.Length;
            var xor = firstHash.Length ^ secondHash.Length;
            for (int i = 0; i < minHashLength; i++)
                xor |= firstHash[i] ^ secondHash[i];
            return xor == 0;
        }
    }

}
